<?php

namespace Admin\Controller;

class ProductController extends AdminController {

//商品管理
    public function index() {

        if(isset($_GET['status'])){
            $status=$_GET['status'];
            $map['status']=$status;
        }
        if(isset($_GET['inventory'])){
            $map['inventory']=array('lt',6);
        }
        if(isset($_GET['recommend'])){
            $map['recommend']=1;
        }
        $name = I('name');
        $sku = I('sku');
        if($sku){
            $map['sku'] = array('like', '%' .$sku . '%');
        }
        $map['name'] = array('like', '%' . (string) $name . '%');
        $list = $this->lists('Product', $map);

        int_to_string($list);
        $this->assign('_list', $list);
        $this->meta_title = '商品数据列表';
        $this->display();
    }

//商品发布
    public function add($sku = "", $name = "", $intro = "", $picarray = "", $quantity = "", $tagarray = "", $quality = "", $proorigin = "", $procycle = "", $prostorage = "", $proinventory = "", $proprice = "", $unitprice = "", $video = "", $content = "") {
        if (IS_POST) {
            $tagstr = implode(',', $tagarray);
//            if ($name == "" || $intro == "" || $quantity == "" || $inventory = "" || $price = ""|| $sku = "") {
//                $this->error("商品信息内容不能为空");
//            }

            $picurlarry = get_picarry_url($picarray);
            $ProductData = array('sku' => $sku, 'name' => $name, 'intro' => $intro, 'picarray' => $picarray, 'picurlarray' => $picurlarry,
                'quantity' => $quantity, 'tagarray' => $tagstr, 'quality' => $quality, 'origin' => $proorigin, 'cycle' => $procycle, 'storage' => $prostorage,
                'inventory' => $proinventory, 'price' => $proprice, 'unitprice' => $unitprice, 'video' => $video,
                'createdate' => NOW_TIME, 'lastupdate' => NOW_TIME, 'content' => $content);
            $pid = M("product")->add($ProductData);
            if (!$pid) {
                $this->error("新商品添加失败！");
            } else {
                $this->success('新商品添加成功！', U('index'));
            }
        } else {
            $lableset = C("LABEL_SET");
            $this->assign("lableset", $lableset);
            $this->display();
        }
    }

//商品编辑
    public function edit($id = "", $sku = "", $name = "", $intro = "", $content = "", $picarray = "", $quantity = "", $tagarray = "", $quality = "", $proorigin = "", $procycle = "", $prostorage = "", $proinventory = "", $proprice = "", $unitprice = "", $video = "") {
        if (IS_POST) {
            $tagstr = implode(',', $tagarray);
            if ($name == "" || $proprice == "") {
                $this->error("商品信息内容不能为空");
            }

            $picurlarray = get_picarry_url($picarray);

            $ProductData = array('sku' => $sku, 'name' => $name, 'intro' => $intro, 'content' => $content, 'picarray' => $picarray,
                'picurlarray' => $picurlarray, 'lastupdate' => NOW_TIME, 'quantity' => $quantity, 'tagarray' => $tagstr, 'quality' => $quality,
                'origin' => $proorigin, 'cycle' => $procycle, 'storage' => $prostorage, 'inventory' => $proinventory, 'price' => $proprice, 'unitprice' => $unitprice, 'video' => $video);
            $Product = D('Product');
            if ($Product->create($ProductData) && $Product->where(array('id' => $id))->save()) {
                $this->success('商品编辑！','javascript:history.back(-1);');
            } else {
                $this->error($Product->getError());
            }
        } else {
            $lableset = C("LABEL_SET");
            $this->assign('lableset', $lableset);
            $data['Product'] = M('Product')->where(array('id' => $id))->find();
            $tagarray = explode(",", $data['Product']['tagarray']);
            $this->assign('tagarray', $tagarray);

            $lable = array();
            $j = 0;
            foreach ($lableset as $key => $value) {

                for ($i = 0; $i < count($tagarray); $i++) {
                    if ($key == $tagarray[$i]) {
                        $lable[$j]['key'] = $key;
                        $lable[$j]['value'] = $value;
                        $lable[$j]['check'] = 1;
                        break;
                    } else {
                        $lable[$j]['key'] = $key;
                        $lable[$j]['value'] = $value;
                        $lable[$j]['check'] = 0;
                    }
                }
                $j++;
            }
            $this->assign("lable", $lable);
            $this->Product = $data['Product'];
            $this->data = $data;
            $this->display();
        }
    }

//删除商品
    public function del($id = "") {
        IF ($id == "") {
            $this->error("商品刪除失败!");
        }
        $Data = array('status' => -1);
        $Product = D('Product');
        if ($Product->where(array('id' => $id))->save($Data)) {
            $this->success("商品刪除成功!");
        } else {
            $this->error("商品刪除失败！");
        }
    }

//上架
    public function puton($id = "") {
        IF ($id == "") {
            $this->error("商品上架失败!");
        }

        $Data = array('status' => 1);
        $Product = D('Product');
        if ($Product->where(array('id' => $id))->save($Data)) {
            $this->success("商品上架成功!");
        } else {
            $this->error("商品上架失败！");
        }
    }

//下架
    public function putoff($id = "") {
        IF ($id == "") {
            $this->error("商品下架失败!");
        }
        $Data = array('status' => 0);
        $Product = D('Product');
        if ($Product->where(array('id' => $id))->save($Data)) {
            $this->success("商品下架成功!");
        } else {
            $this->error("商品下架失败！");
        }
    }

//删除图片ajax
    public function delPicture($id = "") {
        $Productimage = D('Productimage');
        $map['id'] = $id;
        $data['status'] = -1;
        $result = $Productimage->where($map)->save($data);

        if (!$result) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }

    /**
     * 商品主图上传图片
     * @author 曹梦龙
     */
    public function uploadPicture() {
        /* 返回标准数据 */
        $return = array('status' => 1, 'info' => '上传成功', 'data' => '');

        /* 调用文件上传组件上传文件 */
        $Productimage = D('ProductImage');
        $pic_driver = C('PICTURE_UPLOAD_DRIVER');
        /*  $info = $Productimage->upload(
          $_FILES,
          C('PICTURE_UPLOAD'),
          C('PICTURE_UPLOAD_DRIVER'),
          C("UPLOAD_{$pic_driver}_CONFIG")
          );
          dump($info); */

        $Upload = new \Think\Upload(C('PICTURE_UPLOAD'), C('PICTURE_UPLOAD_DRIVER'), C("UPLOAD_{$pic_driver}_CONFIG"));
        $info = $Upload->upload($_FILES);

        /* 记录图片信息 */
        if ($info) {
            $return['status'] = 1;
            $return['url'] = $info['download']['url'];
            $data['fileurl'] = $info['download']['url'];
            $data['createdate'] = NOW_TIME;
            $data['syncStatus'] = 1;
            if ($Productimage->create($data) && ($id = $Productimage->add())) {
                $return['id'] = $id;
            }
            $return = array_merge($info['download'], $return);
        } else {
            $return['status'] = 0;
            $return['info'] = $Picture->getError();
        }

        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }
    
    /**
     * 商品推荐
     * recommend
     */
    public function recommend($id="",$status=""){
        $map['id']=$id;
        $data['recommend']=$status;
        $data['lastupdate']=time();
        $result=M('Product')->where($map)->save($data);
        if($result){
            if($status==1){
                echo 1;
            }else{
             $this->success("商品置顶取消设置成功！");
            }
        }else{
            echo 0;
        }
    }
    public function orderExport(){
//        if(isset($_GET['status'])){
//            $status=$_GET['status'];
//            $map['status']=$status;
//        }
//        if(isset($_GET['inventory'])){
//            $map['inventory']=array('lt',6);
//        }
//        if(isset($_GET['recommend'])){
//            $map['recommend']=1;
//        }
//        $name = I('name');
//        $map['name'] = array('like', '%' . (string) $name . '%');
//        $data = M('Product')->where($map)->getField('sku,name,quantity,intro,price,inventory,origin,from_unixtime(lastupdate)',true);
//        $data = M('Product')->getField('sku,name,quantity,intro,price,inventory,origin,from_unixtime(lastupdate)',true);
        $sql="select sku,name,quantity,intro,price,inventory,origin,from_unixtime(lastupdate),status from gr_product where 1=1 ";
        $data = M('Product')->query($sql);
        if ($data) {
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");
            $filename = "世果商品表";
            $headArr = array("批次","商品名","规格","简介","价格","库存","产地","修改日期","状态(1:上架,0:下架)");
            $this->getExcel($filename, $headArr, $data,'世果商品表（含下架商品）');
        }else{
            $this->error("没有可导出的数据");
        }
    }
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);
        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $objPHPExcel->getActiveSheet()->getStyle($colum . '2')->getFont()->setBold(true);
            $key += 1;
        }
        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
        $objActSheet->getColumnDimension('A')->setWidth(18);
        $objActSheet->getColumnDimension('B')->setWidth(16);
        $objActSheet->getColumnDimension('C')->setWidth(10);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(15);
        $objActSheet->getColumnDimension('F')->setWidth(20);
        $objActSheet->getColumnDimension('G')->setWidth(20);
        $objActSheet->getColumnDimension('H')->setWidth(30);
        $objActSheet->getColumnDimension('I')->setWidth(20);
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
}
